# -*- coding: utf-8 -*-
import hashlib
import os
import time
import zipfile

folder_names = []
info = {}
md5s = []


# 获取文件的md5
def get_file_md5(filepath):
    if not os.path.isfile(filepath):
        return
    my_hash = hashlib.md5()
    f = open(filepath, "rb")
    while True:
        b = f.read(8096)
        if not b:
            break
        my_hash.update(b)
    f.close()
    return my_hash.hexdigest()


#  遍历文件的md5
def create_md5_info(path):
    """
    :param path: 文件夹路径
    :return: md5数组
    """

    # 写入内容
    for root, dirs, files in os.walk(path):
        for name in files:
            temp_path = os.path.join(root, name)
            md5s.append(get_file_md5(temp_path) + " " + temp_path.replace(os.path.dirname(path), "*"))
    return md5s


#  创建 .md5文件
def create_md5_file(path):
    # 打开/创建文件
    f = open(path + ".md5", "w+")
    # 写入内容
    if os.path.isfile(path):
        f.write(get_file_md5(path) + " " + path.replace(os.path.dirname(path) + "\\", "*") + "\n")
    else:
        for md5 in md5s:
            f.write(md5 + "\n")
    # 关闭文件
    f.close()


# 压缩文件
def compressFolder(folderPath):
    """
    :param folderPath: 文件夹路径
    :return:
    """
    compressPathName = folderPath + '.zip'
    zip = zipfile.ZipFile(compressPathName, 'w', zipfile.ZIP_DEFLATED)
    # dict = {}

    # zip.comment = bytes('\n'.join(create_md5_info(folderPath)), encoding="gbk")
    for i in info:
        if isinstance(info[i], list):
            zip.comment = zip.comment + bytes(i + ":\n" + '\n'.join(info[i]) + "\n\n", encoding="gbk")
        else:
            zip.comment = zip.comment + bytes(i + ":" + info[i] + "\n\n", encoding="gbk")
    zip.comment = zip.comment + bytes("创建时间:" + get_current_time() + "\n\n", encoding="gbk")

    for path, dirNames, fileNames in os.walk(folderPath):
        fpath = path.replace(folderPath, '')
        for name in fileNames:
            fullName = os.path.join(path, name)

            name = fpath + '\\' + name
            zip.write(fullName, name)
    zip.comment = zip.comment + bytes("修改时间:" + get_current_time(), encoding="gbk")
    zip.close()


def get_file_size_bytes(filepath):
    # 获取文件大小
    try:
        file_size = os.path.getsize(filepath)
        if file_size > 1048576:
            file_size = file_size / float(1024 * 1024)
            dw = 'MB'
        elif 1024 < file_size <= 1048576:
            file_size = file_size / float(1024)
            dw = 'KB'
        else:
            dw = 'Byte'
        return str(round(file_size, 2)) + dw
    except Exception as err:
        print(err)


def get_file_info(path, tree_date, name):
    # 获取所有文件夹名
    folder_names.append(path.split('\\')[-1])
    # 获取现在时间
    now_time = time.strftime('%Y.%m.%d %H:%M:%S', time.localtime(time.time()))
    # 屏蔽带有以下关键字的文件
    s1 = '~'
    s2 = '.tmp'
    # 获取path目录下所有文件
    fileList = os.listdir(path)
    for filename in fileList:
        # listTemp = []
        i = 0
        # 获取path与filename组合后的路径
        pathTmp = os.path.join(path, filename)
        # 判断是否为目录
        if os.path.isdir(pathTmp):
            # 是目录就继续递归查找
            get_file_info(pathTmp, tree_date, name)
        # 判断是否为文件
        elif os.path.isfile(pathTmp):
            # 过滤临时文件和隐藏文件
            if not (s1 in filename or s2 in filename):
                # 如果是文件，则获取相应文件的大小
                fileSize = get_file_size_bytes(pathTmp)
                # 如果是文件，则获取相应文件的MD5
                fileMd5 = get_file_md5(pathTmp)
                # 如果是文件，则获取相应文件的相对路径
                rpath = path_op(pathTmp, folder_names[0])

                tree_date.insert('', i, values=(filename, rpath, fileSize, fileMd5))
                # listTemp.append(filename)
                # listTemp.append(rpath)
                # listTemp.append(fileSize)
                # listTemp.append(fileMd5)
                # listTemp.append(name)
                # listTemp.append(now_time)
                # lists.extend(listTemp)


def path_op(folder_path, folder_name):
    """
    :param folder_path: 文件路径
    :param folder_name: 文件名
    :return:
    """
    if folder_path.find(folder_name) != -1:
        p = folder_path.find(folder_name)
        return folder_path[p:]


def get_current_time():
    current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    return current_time
